package com.ccxy.springboot.controller;

import com.ccxy.springboot.service.imp.BootServiceImpl;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@RestController
public class downexcelController {
    @Autowired
    private BootServiceImpl service;
    @RequestMapping("/downloadexcel")
    @ResponseBody
    public void downloadexcel(HttpServletResponse response) throws IOException {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("信息表");
        List<Map> student = service.queryselect_info();
        String fileName = "city_info"  + ".xls";//设置要导出的文件的名字
        String[] headers = { "城市名字", "城市编号", "城市码"};
        //headers表示excel表中第一行的表头
        HSSFRow row = sheet.createRow(0);
        //在excel表中添加表头
        for(int i=0;i<headers.length;i++){
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }
        //新增数据行，并且设置单元格数据
        int rowNum = 1;
        for (Map map : student){
            row = sheet.createRow(rowNum);
            row.createCell(0).setCellValue((String) map.get("chinese"));
            row.createCell(1).setCellValue((String) map.get("adcode"));
            row.createCell(2).setCellValue((String) map.get("citycode"));
            rowNum++;
        }
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());

    }
}
